/* eslint-disable @typescript-eslint/no-unused-vars */
import { Device } from "@/api/interface/iot";
import { getRule, getRuleProcessorList, modRule } from "@/api/modules/iot/rule";
import PageHeader from "@/components/Frame/PageHeader";
import SaveClearBtn from "@/components/Frame/save-clear-btn";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { ComponentInternalInstance, defineComponent, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import { dataFormat } from "@/utils/format";
import "./ruleDetail.scss";
import SelectProductList from "@/components/Sansan/SelectProductList";
import SelectDeviceListAll from "@/components/Sansan/SelectDeviceListAll";
import { showTips } from "@/utils/util";
import { RouterPath } from "@/enums/routerPath";
import { gotoPage } from "@/utils/routerUtil";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import GoFlow from "@/components/GoFlow/index.vue";

export default defineComponent({
	emits: [],
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		let route = useRoute();
		const goFlowEl = ref();
		const state = reactive({
			bindType: "product",
			productList: [],
			deviceList: [],
			detail: {
				id: "",
				name: "",
				status: ""
			} as Device.ResRule
		});
		const basicDialog = reactive({
			visible: false,
			title: proxy?.$t("ruledetail.dialog_title.basic"),
			detail: {} as Device.ResRule
		});
		const buttonsList = ref([]);
		onMounted(() => {
			useAuthButtons(route.query.menuId as string).then(val => {
				buttonsList.value = val;
			});

			initPage();
		});
		const initPage = async () => {
			const ruleId = route.query.id as string;
			let ruleInfo = await getRule({ id: ruleId });
			state.detail = ruleInfo.result;
			state.bindType = state.detail.productId ? "product" : "device";

			//多选扩展字段
			state.productList = state.detail.productId?.split(",") || [];
			state.deviceList = state.detail.devSn?.split(",") || [];
			fillRuleLinks();
		};
		const fillRuleLinks = async () => {
			let { result } = await getRuleProcessorList({ ruleId: state.detail.id });
			goFlowEl.value.fillDefault(result.records);
		};
		const changeBindType = () => {
			state.deviceList = [];
			state.detail.devSn = "";
			state.productList = [];
			state.detail.productId = "";
		};
		const submitBasic = async () => {
			state.detail.productId = state.productList.join(",");
			state.detail.devSn = state.deviceList.join(",");
			let { code, message } = await modRule(state.detail);
			showTips(code, proxy?.$t("ruledetail.tips.modify"), message);
		};
		return () => {
			return (
				<div class="rule-detail-page h-full">
					<PageHeader
						showBackText={false}
						v-slots={{
							operate: () => {
								return buttonsList.value.find((menu: any) => menu.path == "mod") ? (
									<SaveClearBtn v-model={basicDialog.visible} onSubmit={() => submitBasic()} />
								) : null;
							}
						}}
					>
						<span>{state.detail.name}</span>
						<OnlineStatus
							v-model={state.detail.status}
							labels={{ enable: proxy?.$t("ruledetail.status.enable"), disable: proxy?.$t("ruledetail.status.disable") }}
							types={{ enable: "success", disable: "danger" }}
							class="ml-4 mr-4"
						/>
						<el-link class="iconfont iconbx-sync ml-2" type="primary" onClick={initPage}>
							{proxy?.$t("ruledetail.btn.refresh")}
						</el-link>
					</PageHeader>
					<div class="mb-4 p-4 bg-white">
						<div class="block-simple pt-4 pb-4">
							<div class="grid grid-cols-4">
								<div class="flex item">
									<div class="info-title text-right w-36">{proxy?.$t("ruledetail.tab_label.name")}</div>
									<div class="info-text flex-1">
										{basicDialog.visible ? (
											<el-input v-model={state.detail.name} placeholder={proxy?.$t("rule_detaildialog.placeholder.name")} />
										) : (
											state.detail.name || "--"
										)}
									</div>
								</div>
								<div class="flex item">
									<div class="info-title text-right w-36">{proxy?.$t("ruledetail.tab_label.update_time")}</div>
									<div class="info-text flex-1">{dataFormat("datetime", state.detail.updateTime)}</div>
								</div>
								<div class="flex item col-span-2">
									{!state.detail.productId && !state.detail.devSn ? (
										<div class="info-title text-right w-36">{proxy?.$t("ruledetail.tab_label.obj")}</div>
									) : null}
									{state.detail.productId ? (
										<div class="info-title text-right w-36">{proxy?.$t("ruledetail.tab_label.product")}</div>
									) : null}
									{state.detail.devSn ? (
										<div class="info-title text-right w-36">{proxy?.$t("ruledetail.tab_label.dev")}</div>
									) : null}
									<div class="info-text flex-1 inline-flex">
										{basicDialog.visible ? (
											<>
												<el-select v-model={state.bindType} onChange={() => changeBindType()}>
													<el-option label={proxy?.$t("ruledetail.option.product")} value="product"></el-option>
													<el-option label={proxy?.$t("ruledetail.option.dev")} value="device"></el-option>
												</el-select>
												{state.bindType == "product" ? (
													<SelectProductList multiple v-model={state.productList} detail={{ type: "all" }} />
												) : null}
												{state.bindType == "device" ? <SelectDeviceListAll multiple v-model={state.deviceList} /> : null}
											</>
										) : (
											<>
												{/* 跳转到产品 */}
												{state.detail.productId?.split(",").map((item: string, i: number) => {
													return (
														<>
															{i > 0 ? <span class="p-1">, </span> : null}
															<el-link type="primary" onClick={() => gotoPage(RouterPath.productDetail, { id: item })}>
																{item}
															</el-link>
														</>
													);
												})}
												{/* 跳转到设备 */}
												{state.detail.devSn?.split(",").map((item: string, i: number) => {
													return (
														<>
															{i > 0 ? <span class="p-1">, </span> : null}
															<el-link type="primary" onClick={() => gotoPage(RouterPath.deviceDetail, { sn: item })}>
																{item}
															</el-link>
														</>
													);
												})}
												{!state.detail.productId && !state.detail.devSn ? (
													<el-link type="primary" underline={false} onClick={() => (basicDialog.visible = true)}>
														{proxy?.$t("ruledetail.btn.config")}
													</el-link>
												) : null}
											</>
										)}
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="flow-config">
						<GoFlow ref={goFlowEl} ruleId={state.detail.id} onReload={() => fillRuleLinks()} />
					</div>
				</div>
			);
		};
	}
});
